namespace SimpleWebServices.Web
{
    using System;
    using System.Collections.Specialized;
    using System.Web;
    using Moq;

    public static class HttpRequestBaseTestingExtensionMethods
    {
        public static void SetAcceptTypes(this HttpRequestBase request, string[] types)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            Mock.Get(request)
                .Setup(req => req.AcceptTypes)
                .Returns(types);
        }

        public static void SetHeaders(this HttpRequestBase request, string name, string value)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            NameValueCollection headers = new NameValueCollection();
            headers.Add(name, value);

            Mock.Get(request)
                .Setup(req => req.Headers)
                .Returns(headers);
        }

        public static void SetHeaders(this HttpRequestBase request, NameValueCollection headers)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            Mock.Get(request)
                .Setup(req => req.Headers)
                .Returns(headers);
        }

        public static void SetHttpMethod(this HttpRequestBase request, string method)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            Mock.Get(request)
                .Setup(req => req.HttpMethod)
                .Returns(method);
        }

        public static void SetHttpRequestUrl(this HttpRequestBase request, string path)
        {
            if (null == path)
            {
                throw new ArgumentNullException("path");
            }

            if (!path.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\".");
            }

            var mock = Mock.Get(request);

            mock.Setup(req => req.QueryString)
                .Returns(path.ToQueryString());
            mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
                .Returns(path.ToAppRelativeCurrentExecutionFilePath());
            mock.Setup(req => req.PathInfo)
                .Returns(string.Empty);
            mock.Setup(req => req.Url)
                .Returns(new Uri(new Uri("http://example.net"), new Uri(path.Substring(1), UriKind.Relative)));
        }
    }
}